<template>
	<div>
		<el-row :gutter="5">
			<!-- 资源类型 -->
			<el-col :span="5">
				<el-card shadow="never">
					<el-button v-auth="'sys:resourcetype:add'" type="primary" @click="openResourceTypeDialog">
						<el-icon class="mr-2">
							<ele-circle-plus />
						</el-icon>
						新增资源类型
					</el-button>
					<el-input
						v-model="resourceTypeData.params.keyword"
						clearable
						@clear="getResourceTypeList"
						@change="getResourceTypeList"
						class="mt-3"
						placeholder="输入资源类型名称搜索"
					>
						<template #prefix>
							<el-icon>
								<ele-search />
							</el-icon>
						</template>
					</el-input>
					<div class="resource-type-list mt-3 mb-3">
						<template v-if="resourceTypeData.data.length > 0">
							<div
								v-for="item in resourceTypeData.data"
								:key="item.id"
								:class="tableData.params?.resourceTypeCode === item.code ? 'selected' : ''"
								class="resource-type-item justify-between flex"
								@click="pickResourceType(item.code)"
							>
								<span>{{ item.name }}</span>
								<span class="color-info font12">{{ item.code }}</span>
								<div class="resource-type-operation">
									<el-button v-auth="'sys:resourcetype:update'" size="small" @click="openResourceTypeDialog(item)">
										<el-icon>
											<ele-edit />
										</el-icon>
									</el-button>
									<el-button v-auth="'sys:resourcetype:delete'" size="small" @click="delResourceType(item)">
										<el-icon>
											<ele-delete />
										</el-icon>
									</el-button>
								</div>
							</div>
						</template>
						<div v-else class="color-info font12 mt-5 flex items-center justify-center">暂无数据</div>
					</div>
				</el-card>
			</el-col>
			<!-- 资源列表 -->
			<el-col :span="18">
				<el-card shadow="never">
					<el-button
						v-auth="'sys:resource:add'"
						v-if="tableData.params?.resourceTypeCode && tableData.params?.resourceTypeCode !== '0'"
						type="primary"
						@click="openResourceDialog"
						class="mb-3"
					>
						<el-icon class="mr-2">
							<ele-circle-plus />
						</el-icon>
						新增资源
					</el-button>
					<el-table v-loading="tableData.isLoading" :data="tableData.data" border style="width: 100%" row-key="id">
						<el-table-column prop="_tableIndex" label="序号" align="center" width="60" />
						<el-table-column prop="name" label="资源名称" align="center" />
						<el-table-column prop="version" label="版本" align="center" width="80" />
						<el-table-column prop="resourceTypeCode" label="类别名称" align="center" />
						<el-table-column prop="grade" label="年级" align="center" />
						<el-table-column prop="className" label="班别" align="center" />
						<el-table-column prop="createTime" label="创建时间" align="center" width="170" />
						<el-table-column label="操作" fixed="right" align="center" width="220">
							<template #default="{ row }">
								<el-button v-auth="'sys:resource:update'" link type="primary" @click="openResourceDialog(row)">
									<el-icon><ele-edit /></el-icon>修改
								</el-button>
								<el-button v-auth="'sys:resource:dalete'" link type="danger" @click="delResource(row.id)">
									<el-icon><ele-delete /></el-icon>删除
								</el-button>
								<el-button v-auth="'sys:resource:download'" link type="primary" @click="downloadResource(row)">
									<el-icon><ele-download /></el-icon>下载
								</el-button>
							</template>
						</el-table-column>
					</el-table>
					<Pagination
						:total="pageData.total"
						:currentPage="pageData.pageIndex"
						v-model:pageSize="pageData.pageSize"
						layout="total, sizes, prev, pager, next, jumper"
						@changePage="changePage"
						@SizeChange="handleSizeChange"
						@update:page-size="handleSizeChange"
					/>
				</el-card>
			</el-col>
		</el-row>

		<ResourceDialog
			ref="resourceDialogRef"
			:resourceTypeCode="tableData.params?.resourceTypeCode"
			:typeList="resourceTypeData.data"
			@refresh="getResourceList"
		/>
		<ResourceTypeDialog ref="resourceTypeDialogRef" @refresh="getResourceTypeList" />
	</div>
</template>

<script setup>
import ResourceDialog from './components/ResourceDialog.vue';
import ResourceTypeDialog from './components/ResourceTypeDialog.vue';
import { getResourcePageApi, getResourceTypeListApi, deleteResourceTypeApi, deleteResourceApi, downloadResourceApi } from '@/api/resource';
import { reactive, ref } from 'vue';
import { calcTableIndex } from '@/utils';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';

/** 分页 */
const pageData = reactive({
	pageIndex: 1,
	pageSize: 10,
	total: 0,
});

const changePage = (page) => {
	pageData.pageIndex = page;
	getResourceList();
};

const handleSizeChange = (page) => {
	pageData.pageSize = page;
	getResourceList();
};

/** 表格 */
const tableData = reactive({
	data: [],
	isLoading: false,
	params: {
		resourceTypeCode: '',
	},
});

// 获取表格列表
const getResourceList = () => {
	tableData.isLoading = true;
	getResourcePageApi({ ...pageData, ...tableData.params }).then((res) => {
		tableData.data = calcTableIndex(res, pageData);
		pageData.total = res.total;
		tableData.isLoading = false;
	});
};

/** 资源类型 */
const resourceTypeData = reactive({
	data: [],
	params: {
		pageSize: 666,
		keyword: '',
	},
});

// 获取字典类型列表
function getResourceTypeList() {
	getResourceTypeListApi(resourceTypeData.params).then((res) => {
		resourceTypeData.data = res || [];
	});
}

const delResourceType = (row) => {
	ElMessageBox.confirm('是否确认删除本条数据？', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			deleteResourceTypeApi(row.id)
				.then(() => {
					ElMessage.success('删除成功');
					getResourceTypeList();
				})
				.catch((error) => {
					ElMessage.error('删除失败');
					console.error('[delResourceType] 删除接口错误：', error);
				});
		})
		.catch(() => {
			console.log('[delResourceType] 用户取消删除');
		});
};

const downloadResource = async (row) => {
	let loading = null;
	try {
		loading = ElLoading.service({
			lock: true,
			text: '文件下载准备中...',
			background: 'rgba(0, 0, 0, 0.7)',
		});

		// 调用下载接口（已通过axios拦截器处理响应）
		const response = await downloadResourceApi(row.id);

		// 处理错误响应（增强版）
		if (!response || response.status !== 200 || response.error) {
			const errorMsg = response?.error?.msg || response?.data?.error?.msg || `文件下载失败 (状态码: ${response?.status || '无响应'})`;
			throw new Error(errorMsg);
		}

		// 严格校验响应数据类型
		if (!response.data || !(response.data instanceof Blob)) {
			console.error('无效的响应数据格式:', response);
			throw new Error('无效的响应数据格式');
		}

		// 使用拦截器返回的文件名和内容类型
		const fileName = response.filename || `resource_${Date.now()}`;
		const blob = new Blob([response.data], { type: response.contentType });

		// 创建并触发下载
		const link = document.createElement('a');
		link.href = URL.createObjectURL(blob);
		link.download = fileName;
		link.style.display = 'none';
		document.body.appendChild(link);
		link.click();

		// 异步清理资源
		setTimeout(() => {
			URL.revokeObjectURL(link.href);
			document.body.removeChild(link);
		}, 100);

		ElMessage.success('文件下载成功');
		// 延迟1秒关闭loading让用户感知完成状态
		setTimeout(() => loading?.close(), 1000);
	} catch (error) {
		// 增强错误处理
		let errorMsg = error.message;
		if (error.name === 'AbortError') {
			errorMsg = '下载已取消';
		} else if (error.message.includes('Network Error')) {
			errorMsg = '网络连接异常，请检查网络后重试';
		} else if (error.message.includes('无效的响应数据格式')) {
			errorMsg = '服务器返回了无效的文件格式';
		}
		ElMessage.error(`下载失败: ${errorMsg}`);
		console.error('[downloadResource] 下载错误：', {
			error: error.stack,
			response: error.response?.data,
		});
	} finally {
		loading?.close();
	}
};

// 删除资源
const delResource = (id) => {
	ElMessageBox.confirm('删除操作将同时删除资源记录和关联的物理文件（如果存在），是否确认删除？', '删除确认', {
		confirmButtonText: '确认删除',
		cancelButtonText: '取消',
		type: 'warning',
		confirmButtonClass: 'el-button--danger',
	})
		.then(() => {
			deleteResourceApi(id)
				.then(() => {
					ElMessage.success('删除成功');
					getResourceList();
				})
				.catch((error) => {
					const msg = error.response?.data?.msg || error.message || '删除失败';
					ElMessage.error(msg);
					console.error('[delResource] 删除接口错误：', error);
				});
		})
		.catch(() => {
			console.log('[delResource] 用户取消删除');
		});
};

/** 弹框 */
const resourceDialogRef = ref();
const openResourceDialog = (data = {}) => {
	resourceDialogRef.value.openDialog({
		...data,
		Code: tableData.params.resourceTypeCode,
		typeList: resourceTypeData.data,
	});
};

const resourceTypeDialogRef = ref();
const openResourceTypeDialog = (data = {}) => {
	resourceTypeDialogRef.value.openDialog(data);
};

const pickResourceType = (code) => {
	tableData.params.resourceTypeCode = code;
	pageData.pageIndex = 1; // 重置分页到第一页
	getResourceList();
};

getResourceTypeList();
</script>

<style lang="scss" scoped>
.resource-type-list {
	height: calc(100vh - 230px);
	overflow-y: auto;

	.resource-type-item {
		cursor: pointer;
		padding: 0 10px;
		height: 30px;
		position: relative;

		&.selected {
			background-color: #eaeefe;
		}

		&:hover {
			background-color: #f5f7fa;

			.resource-type-operation {
				display: flex;
				align-items: center;
			}
		}

		.resource-type-operation {
			position: absolute;
			right: 10px;
			top: 0;
			z-index: 10;
			height: 100%;
			background-color: #f5f7fa;
			display: none;
		}
	}
}
</style>
